package com.cy.study.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cy.study.common.CommonConstant;
import com.cy.study.entity.AdminInfoEntity;
import com.cy.study.exception.BusinessException;
import com.cy.study.mapper.AdminInfoMapper;
import com.cy.study.req.AdminLoginReq;
import com.cy.study.service.AdminInfoService;
import com.cy.study.util.CacheTool;
import com.cy.study.util.PasswordEncodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class AdminInfoServiceImpl extends ServiceImpl<AdminInfoMapper, AdminInfoEntity> implements AdminInfoService {

    private final CacheTool cacheTool;

    @Override
    public String adminLogin(AdminLoginReq req) {
        String telephone = req.getTelephone();
        String unCode = req.getPassword();
        String enCode = PasswordEncodeUtil.passwordEncode(unCode, CommonConstant.PASSWORD_SALT);
        QueryWrapper<AdminInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AdminInfoEntity::getTelephone,telephone)
                .eq(AdminInfoEntity::getPassword,enCode);
        AdminInfoEntity entity = this.getBaseMapper().selectOne(wrapper);
        if(ObjectUtil.isNull(entity)){
            throw new BusinessException("管理员手机号或者密码错误");
        }
        Map<String,Object> payloads = new HashMap<>();
        payloads.put("userId",entity.getAdminId());
        long l = System.currentTimeMillis() / 100 + CommonConstant.TOKEN_VALID_SECONDS;
        System.out.println(l);
        payloads.put("exp",l);
        String token = JWTUtil.createToken(payloads, CommonConstant.TOKEN_SIGN_KEY.getBytes());
        //加入缓存
        cacheTool.add(CommonConstant.TOKEN_PREFIX+entity.getAdminId(),token);
        return token;
    }
}
